package com.purong.purong.fragment;

import android.content.Intent;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.purong.purong.Contant;
import com.purong.purong.R;
import com.purong.purong.activity.ArticleDetActivity;
import com.purong.purong.adapter.ArticleCollectAdapter;
import com.purong.purong.bean.ArticleBean;
import com.purong.purong.bean.ArticleCollectBean;
import com.purong.purong.bean.CreditDetBean;
import com.purong.purong.widget.LoadingView;
import com.yao.sdk.net.ResponseInfo;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import in.srain.cube.views.ptr.PtrCustomHandler;
import in.srain.cube.views.ptr.PtrDefaultCustomHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrPuRongLayout;

/**
 * Created by zengwenjie on 2017/12/4.
 */
public class ArticleCollectFragment extends BaseFragment{
    private RecyclerView mRecyclerView;
    private ArticleCollectAdapter mAdapter;
    private List<ArticleBean> articleList =new ArrayList<>();
    private PtrPuRongLayout mPtrFrame;
    private LoadingView loadView;
    private int page = 1;
    @Override
    public int getRootViewId() {
        return R.layout.fragment_article_collect;
    }

    @Override
    public void initView(View rootView) {
        loadView = (LoadingView) rootView.findViewById(R.id.loading_view);
        loadView.setNoResultToast("暂无收藏的资讯", "");
        loadView.setLoadListener(new LoadingView.OnLoadListener() {
            @Override
            public void onReload() {
                getArticle(true);
            }

            @Override
            public void onRefresh() {

            }
        });
        mRecyclerView=(RecyclerView)rootView.findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter=new ArticleCollectAdapter(getActivity());
        mAdapter.setData(articleList);
        mAdapter.setOnInfoItemClickListener(new ArticleCollectAdapter.OnArticleItemClickListener() {
            @Override
            public void onArticleClick(int position) {
                Intent intent=new Intent(getActivity(), ArticleDetActivity.class);
                intent.putExtra("ARTICLE_ID", articleList.get(position).getArticle_id());
                intent.putExtra("NEED_BACK",true);
                startActivityForResult(intent,1);
            }

            @Override
            public void onDelete(int position) {
                cancelFavourite(articleList.get(position).getArticle_id());
            }
        });
        mRecyclerView.setAdapter(mAdapter);
        mPtrFrame = (PtrPuRongLayout) rootView.findViewById(R.id.rotate_header_list_view_frame);
        mPtrFrame.setPtrHandler(new PtrCustomHandler() {
            @Override
            public boolean checkCanDoLoadMore(PtrFrameLayout frame, View content, View footer) {
                if (articleList.size() == 0) {
                    return false;
                } else {
                    return PtrDefaultCustomHandler.checkContentCanBePulledUp(frame, content, footer);
                }

            }

            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                getArticle(false);

            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                getArticle(true);
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return false;
//                return (isRequesting||loanList.size()>0)?false:true;
            }
        });

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1){
            if (resultCode==getActivity().RESULT_OK){
                ArticleBean bean=(ArticleBean)data.getSerializableExtra("ARTICLE");
                for (int i = 0; i <articleList.size() ; i++) {
                    if (articleList.get(i).getArticle_id().equals(bean.getArticle_id())){
                        if (bean.getIs_favorite().equals("1"))
                            articleList.remove(i);
                        break;
                    }

                }
                mAdapter.notifyDataSetChanged();
                if (articleList.size() == 0) {
                    loadView.noResult();
                }
            }
        }
    }
    private void cancelFavourite(String id){
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("article_id",id);
        request(Contant.ARTICLE_FAVORITE_CANCEL, params, true, true);
    }
    private void getArticle(boolean clear){
        Map<String, String> params = new LinkedHashMap<String, String>();
        if (clear){
            page=1;
            articleList.clear();
            mAdapter.notifyDataSetChanged();
            loadView.loading();
        }
        params.put("page", page+"");
        if (!request(Contant.USER_ARTICLE_FAVORITE, params, true)) {
            if (clear)
                loadView.fail();
            if (!hasDestroy())
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        if (mPtrFrame.isRefreshing()) {
                            mPtrFrame.refreshComplete();
                        }
                    }
                }, 100);
        }
    }

    @Override
    public void onResponse(ResponseInfo responseInfo) {
        if (hasDestroy())
            return;
        super.onResponse(responseInfo);
        if (responseInfo.url.equals(Contant.USER_ARTICLE_FAVORITE)){
            if (mPtrFrame.isRefreshing()) {
                mPtrFrame.refreshComplete();
            }
            if (responseInfo.isRequestOk){
                try{
                    ArticleCollectBean bean= JSON.parseObject(responseInfo.content,ArticleCollectBean.class);
                    if (bean != null && bean.getArticle_list() != null) {
                        if (bean.getArticle_list().size() > 0)
                            page++;
                        articleList.addAll(bean.getArticle_list());
                        mAdapter.notifyDataSetChanged();

                    }
                    if (articleList.size() == 0) {
                        loadView.noResult();

                    } else {
                        loadView.finish();
                    }
                }catch (Exception e){
                    if (page == 1) {
                        loadView.fail();
                    }
                }
            }else {
                if (page == 1) {
                    loadView.fail();
                }
            }
        }else if (responseInfo.url.equals(Contant.ARTICLE_FAVORITE_CANCEL)){
            if (responseInfo.isRequestOk){
                try{
                    String id=responseInfo.params.get("article_id");
                    for (int i = 0; i < articleList.size() ; i++) {
                        if (articleList.get(i).getArticle_id().equals(id)){
                            articleList.remove(i);
                            break;
                        }

                    }
                    mAdapter.notifyDataSetChanged();
                    if (articleList.size() == 0) {
                        loadView.noResult();

                    }
                }catch (Exception e){

                }
            }
        }
    }

    @Override
    public void initData() {
        getArticle(true);
    }
}
